//
//  YJCategoryViewController.m
//  SnackCourier
//
//  Created by qianfeng01 on 15/7/17.
//  Copyright (c) 2015年 qianfeng01. All rights reserved.
//

#import "YJCategoryViewController.h"
#import "YJCategoryListCell.h"
#import "YJCategoryProductListCell.h"

#import "YJCategoryModel.h"
#import "YJlabelTitleModel.h"
#import "YJcategoryBelowModel.h"

#import "CreateSales.h"

#import "YJcateClassController.h"
#import "YJcateDetaViewController.h"

@interface YJCategoryViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>

@property (nonatomic,strong)NSMutableArray *dataArray;


@property(nonatomic,strong)NSMutableArray *categoryArray;
@property(nonatomic,strong)NSMutableArray *belowArray;

@property(nonatomic,strong)NSMutableArray *lableArray;

@property(nonatomic,strong)UISearchBar *Searchbar;
@end

@implementation YJCategoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArray =[[NSMutableArray alloc] init];
    self.categoryArray=[[NSMutableArray alloc]init];
    
    self.lableArray =[[NSMutableArray alloc]init];
    
    [self createSearchBar];
    [self createView];
    [self createHttpRequest];
    [self createData:kCategoryUrl];
    [self refreshData:kCategoryUrl];
}
-(void)createSearchBar{
    self.Searchbar =[[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width-10, 30)];
    self.Searchbar.delegate =self;
    [self.Searchbar setPlaceholder:@"零食搜索"];
    self.Searchbar.translucent =YES;
    self.navigationItem.titleView = self.Searchbar;
    
}
-(void)createView{
    self.tableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-64)style:(UITableViewStylePlain)];
    self.tableView.dataSource=self;
    self.tableView.delegate =self;
    self.tableView.separatorStyle =NO;
    [self.tableView registerNib:[UINib nibWithNibName:@"YJCategoryListCell" bundle:nil] forCellReuseIdentifier:@"YJCategoryListCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"YJCategoryProductListCell" bundle:nil] forCellReuseIdentifier:@"YJCategoryProductListCell"];
    
    [self.view addSubview:self.tableView];
}
-(void)createData:(NSString *)url{
    
    NSString *path =[YJHelper getFullPathWithFile:url];
    
    BOOL isExist =[[NSFileManager defaultManager] fileExistsAtPath:path];
    BOOL isTimeout =[YJHelper isTimeOutWithFile:url timeOut:24*60*60];
    if ((isExist==YES)&&(isTimeout==NO) ){
        NSData *data =[NSData dataWithContentsOfFile:[YJHelper getFullPathWithFile:url]];
        if (self.currentPage==1) {
            [self.dataArray removeAllObjects];
            [self.categoryArray removeAllObjects];
            [self.belowArray removeAllObjects];
            [self.lableArray removeAllObjects];
        }
        NSDictionary *dicts =[NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSDictionary *datadict=dicts[@"data"];
        NSArray *categoryArry =datadict[@"categoryList"];
        for (NSDictionary *dict in categoryArry) {
            
            YJCategoryModel *mode =[[YJCategoryModel alloc] init];
            [mode setValuesForKeysWithDictionary:dict];
            [self.categoryArray addObject:mode];
        }
        [self.dataArray addObject:self.categoryArray];
        NSArray *ProductListArry=datadict[@"categoryProductList"];
        for (NSDictionary *dict in ProductListArry) {
            YJlabelTitleModel *model =[[YJlabelTitleModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [self.lableArray addObject:model];
            NSArray *arry =dict[@"productList"];
            
            for (NSDictionary *dicte in arry) {
                YJcategoryBelowModel *model =[[YJcategoryBelowModel alloc] init];
                [model setValuesForKeysWithDictionary:dicte];
                [self.belowArray addObject:model];
                
            }
            [self.dataArray addObject:self.belowArray];
        }
        [self.tableView reloadData];
        [self endRefreshing];
        return;
    }
    __weak typeof(self)weakSelf =self;
    [self.manager GET:kCategoryUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if (responseObject) {
            [weakSelf.dataArray removeAllObjects];
            [weakSelf.categoryArray removeAllObjects];
            [weakSelf.belowArray removeAllObjects];
            [weakSelf.lableArray removeAllObjects];
            NSDictionary *dicts =[NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
            NSDictionary *data=dicts[@"data"];
            NSArray *categoryArry =data[@"categoryList"];
            for (NSDictionary *dict in categoryArry) {
                YJCategoryModel *mode =[[YJCategoryModel alloc] init];
                [mode setValuesForKeysWithDictionary:dict];
                [weakSelf.categoryArray addObject:mode];
            }
            [weakSelf.dataArray addObject:weakSelf.categoryArray];
            NSArray *ProductListArry=data[@"categoryProductList"];
            for (NSDictionary *dict in ProductListArry) {
                YJlabelTitleModel *model =[[YJlabelTitleModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                [weakSelf.lableArray addObject:model];
                 NSArray *arry =dict[@"productList"];
                weakSelf.belowArray=[[NSMutableArray alloc]init];
                 for (NSDictionary *dicte in arry) {
                    YJcategoryBelowModel *model =[[YJcategoryBelowModel alloc] init];
                    [model setValuesForKeysWithDictionary:dicte];
                    [weakSelf.belowArray addObject:model];
                
              }
                [weakSelf.dataArray addObject:weakSelf.belowArray];
                
            }
            [weakSelf.tableView reloadData];
        }
        [weakSelf endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

-(void)refreshData:(NSString *)urlStr{
    __weak typeof(self) weakSelf=self;//声明弱引用
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        //重新下载数据
        if (weakSelf.isRefreshing) {
            return ;
        }
        weakSelf.isRefreshing=YES;//标记正在刷新
        [weakSelf createData:urlStr];
    }];
}
-(void)endRefreshing{
    if (self.isRefreshing) {
        //正在刷新，就结束刷新
        self.isRefreshing=NO;//标记刷新结束
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultNone];
    }
}


#pragma mark -<UITableViewDelegate>
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        YJCategoryListCell *cell=[tableView dequeueReusableCellWithIdentifier:@"YJCategoryListCell" forIndexPath:indexPath];
        [cell showDataWithArray:self.categoryArray myblock:^(YJCategoryModel *model) {
            YJcateClassController *controller =[[YJcateClassController alloc] init];
            controller.title =model.cateName;
            controller.id =model.id;
            [self.navigationController pushViewController:controller animated:YES];
        }];
        return cell;
    }else {
        YJCategoryProductListCell *cell=[tableView dequeueReusableCellWithIdentifier:@"YJCategoryProductListCell" forIndexPath:indexPath];
        [cell showDataWithArray:self.dataArray[indexPath.section] myblock:^(NSInteger id) {
            YJImmediatelygrabController *controller =[CreateSales createVC:id];
            controller.title =@"商品详情";
            [self.navigationController pushViewController:controller animated:YES];
        }];
        return cell;
    }

}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        return 270;
    }else{
        return 310;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==0) {
        UIView *view =[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
        view.backgroundColor =[UIColor whiteColor];
        UIView *redView =[[UIView alloc] initWithFrame:CGRectMake(10, 8, 3, 14)];
        redView.backgroundColor =[UIColor redColor];
        redView.layer.masksToBounds=YES;
        redView.layer.cornerRadius =2;
        [view addSubview:redView];
        
        UILabel *label =[[UILabel alloc] initWithFrame:CGRectMake(redView.frame.size.width+10, 8, 200, 14)];
        label.text =@"零食分类";
        [view addSubview:label];
        return view;
    }else{
        UIView *view =[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
        view.backgroundColor =[UIColor whiteColor];
        UIView *redView =[[UIView alloc] initWithFrame:CGRectMake(10, 8, 3, 14)];
        redView.backgroundColor =[UIColor redColor];
        redView.layer.masksToBounds=YES;
        redView.layer.cornerRadius =2;
        [view addSubview:redView];
        UILabel *label =[[UILabel alloc] initWithFrame:CGRectMake(redView.frame.size.width+10, 8, 200, 14)];
        YJlabelTitleModel *model =self.lableArray[section-1];
        label.text =[NSString stringWithFormat:@"精挑细选-%@",model.cateName];
        [view addSubview:label];
        
        UIButton *button =[UIButton buttonWithType:(UIButtonTypeSystem)];
        button.frame = CGRectMake(view.frame.size.width-100, 0, 100, 30);
        UIImage *image =[UIImage imageNamed:@"more"];
        image =[image imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
        [button setImage:image forState:(UIControlStateNormal)];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        button.tag =101+section-1;
        [view addSubview:button];
        return view;
    }
}


-(void)buttonClick:(UIButton *)button{
    YJcateDetaViewController *controller =[[YJcateDetaViewController alloc] init];
    YJlabelTitleModel *model = self.lableArray[button.tag-101];
    controller.labmodel =model;
    [self.navigationController pushViewController:controller animated:YES];
    
}

#pragma mark-
-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    [searchBar setShowsCancelButton:YES animated:YES];
    return YES;
}
-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    [searchBar setShowsCancelButton:NO animated:YES];
    return YES;
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    searchBar.text=@"";
    [searchBar resignFirstResponder];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    YJcateDetaViewController *controller=[[YJcateDetaViewController alloc] init];
    self.currentPage=0;
    controller.key =searchBar.text;
    [self.navigationController pushViewController:controller animated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
